using AutoMapper;
using MediatR;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Writh.Command.Permissions;

namespace RBAC.Api.Writh.CommandHandler.Permissions
{
    public class DeletePermissionCommandHandler : IRequestHandler<DeletePermissionCommand, APIResult<object>>
    {
        private readonly IBaseRepositry<Permission> dal;
        private readonly IMapper mapper;
        private readonly ILogger<DeletePermissionCommandHandler> logger;

        public DeletePermissionCommandHandler(IBaseRepositry<Permission> baseRepositry, IMapper mapper, ILogger<DeletePermissionCommandHandler> logger)
        {
            dal = baseRepositry;
            this.mapper = mapper;
            this.logger = logger;
        }
        
        public async Task<APIResult<object>> Handle(DeletePermissionCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = ResultCode.Success;
            result.Message = "删除权限成功";

            // 获取权限实体
            var permission = dal.GetAll().FirstOrDefault(p => p.Id == request.Id);
            if (permission == null)
            {
                result.Code = ResultCode.Fail;
                result.Message = $"未找到ID为{request.Id}的权限";
                return result;
            }

            // 逻辑删除
            permission.IsDeleted = true;
            permission.ModifyTime = DateTime.Now;
            
            logger.LogInformation("逻辑删除权限开始，ID: {Id}", request.Id);
            await dal.Update(permission);
            return await Task.FromResult(result);
        }
    }
} 